﻿using System;
using System.IO;
using System.Windows.Forms;
using System.Runtime.Serialization.Json;
using System.Threading;
using Microsoft.Win32;

public partial class MainForm : Form
{
    private string this_path = Application.StartupPath;
    private int window_layout_type = 1;//1或2

    public MainForm()
    {
        InitializeComponent();

        //Log.set_log_txt(txt_log);
        init();
    }

    //获取默认浏览器的路径
    private String DefaultWebBrowserFilePath()
    {
        RegistryKey key = Registry.ClassesRoot.OpenSubKey("http\\shell\\open\\command", false);
        String path = key.GetValue("").ToString();
        if (path.Contains("\""))
        {
            path = path.TrimStart('"');
            path = path.Substring(0, path.IndexOf('"'));
        }
        key.Close();
        return path;
    }

    private void init()
    {
        //创建配置文件
        bool isNewConfig = FileManager.createFile(this_path + Config.CONFIG_PATH);
        //无配置时，写入默认配置
        if (isNewConfig)
        {
            ConfigManager.WriteIniData("SVNCOMMAND", "value", Environment.GetEnvironmentVariable("svn_cmd"));
            ConfigManager.WriteIniData("KINDS", "value", "0");
            ConfigManager.WriteIniData("CHANNEL", "value", "default,default2");
            ConfigManager.WriteIniData("CLIENT_COUNT", "value", "4");
            ConfigManager.WriteIniData("USER", "kind", "");
            ConfigManager.WriteIniData("USER", "globalinfo", "");
            ConfigManager.WriteIniData("USER", "resolutionx", "800");
            ConfigManager.WriteIniData("USER", "resolutiony", "450");
            ConfigManager.WriteIniData("USER", "clients", "1,1,1,1");
            ConfigManager.WriteIniData("USER", "reopen", "1");
            ConfigManager.WriteIniData("OPEN_TYPE", "value", "客户端,浏览器");
            ConfigManager.WriteIniData("USER", "type", "客户端");
            ConfigManager.WriteIniData("URL", "value", "www.baidu.com");
            ConfigManager.WriteIniData("PATH", "value", "pc_client_prefix_");
            ConfigManager.WriteIniData("SVN_PATH", "value", "https://svn_pc_client_path");
        }

        string kinds = ConfigManager.ReadIniData("KINDS", "value", "");
        string CHANNEL = ConfigManager.ReadIniData("CHANNEL", "value", "");
        string clientcount = ConfigManager.ReadIniData("CLIENT_COUNT", "value", "");
        string kind = ConfigManager.ReadIniData("USER", "kind", "");
        string globalinfo = ConfigManager.ReadIniData("USER", "globalinfo", "");
        string resolutionx = ConfigManager.ReadIniData("USER", "resolutionx", "");
        string resolutiony = ConfigManager.ReadIniData("USER", "resolutiony", "");
        string clients = ConfigManager.ReadIniData("USER", "clients", "");
        string reopen = ConfigManager.ReadIniData("USER", "reopen", "");
        string open_types = ConfigManager.ReadIniData("OPEN_TYPE", "value", "");
        string open_type = ConfigManager.ReadIniData("USER", "type", "");

        combox_kind.DataSource = kinds.Split(',');
        combox_kind.Text = kind;

        combox_globalinfo.DataSource = CHANNEL.Split(',');
        combox_globalinfo.Text = globalinfo;
        input_resolutionx.Text = resolutionx;
        input_resolutiony.Text = resolutiony;
        checkbox_reopen.Checked = reopen == "1";
        combo_opentype.DataSource = open_types.Split(',');
        combo_opentype.Text = open_type;

        //创建单选框
        listview_c.Items.Clear();
        for (int i = 0; i < get_clients_count(); i++)
        {
            listview_c.Items.Add("" + (i + 1));

        }
        //设置单选框状态
        string[] clientsArr = clients.Split(',');
        for (int i = 0; i < get_clients_count(); i++)
        {
            if (clientsArr.Length > i)
            {
                bool b = clientsArr[i] == "1";
                listview_c.Items[i].Checked = b;
            }
            else
            {
                listview_c.Items[i].Checked = true;
            }
        }

        radiobtn_pingpu.Checked = true;
    }

    private void btn_create_client_Click(object sender, EventArgs e)
    {
        string svn_path = ConfigManager.ReadIniData("SVN_PATH", "value", "");
        string path = ConfigManager.ReadIniData("PATH", "value", "");
        if (!valid_svn_cmd())
        {
            MessageBox.Show("请先选择svn_command的路径");
            select_svn_cmd();
            if (!valid_svn_cmd())
            {
                return;
            }
        }

        string s = "@echo off";
        for (int i = 0; i < get_clients_count(); i++)
        {
            string delete = "rd /s /q " + this_path + "\\" + path + (i + 1) + "\\";
            string checkout = "\"" + get_svn_cmd() + "\\svn.exe\" checkout " + svn_path + " " + this_path + "\\" + path + (i + 1) + "\\";
            string xcopy = "xcopy " + this_path + "\\" + path + "1 " + this_path + "\\" + path + (i + 1) + "\\ /s /e /h";
            if (i == 0)
            {
                s += "\n" + delete;
                s += "\n" + checkout;
            }
            else
            {
                s += "\n" + delete;
                s += "\n" + xcopy;
            }
        }

        if (have_enough_clients())
        {
            MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
            DialogResult dr = MessageBox.Show("你已经有足够的客户端，要[重新创建]?", "", messButton);
            if (dr == DialogResult.OK)
            {
                Utils.do_cmd(s);
                MessageBox.Show("客户端[重新创建]完成");
            }
        }
        else
        {
            MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
            DialogResult dr = MessageBox.Show("确定[创建]客户端?", "", messButton);
            if (dr == DialogResult.OK)
            {
                Utils.do_cmd(s);
                MessageBox.Show("客户端[创建]完成");
            }
        }
    }

    private void btn_add_client_Click(object sender, EventArgs e)
    {
        string path = ConfigManager.ReadIniData("PATH", "value", "");
        if (have_enough_clients())
        {
            MessageBox.Show("你已经有足够的客户端，不需要追加！", "");
        }
        else
        {
            if (!Directory.Exists(this_path + "\\" + path + "1"))
            {
                MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                DialogResult dr = MessageBox.Show("没有" + path + "1，需要全部重新创建，点击确定后开始", "", messButton);
                if (dr == DialogResult.OK)
                {
                    btn_create_client_Click(null, null);
                }
            }
            else
            {
                MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                DialogResult dr = MessageBox.Show("确定[追加]客户端?", "", messButton);
                if (dr == DialogResult.OK)
                {
                    string s = "@echo off";
                    for (int i = 0; i < get_clients_count(); i++)
                    {
                        if (!Directory.Exists(this_path + "\\" + path + (i + 1)))
                        {
                            string xcopy = "xcopy " + this_path + "\\" + path + "1 " + this_path + "\\" + path + (i + 1) + "\\ /s /e /h";
                            s += "\n" + xcopy;
                        }
                    }
                    Utils.do_cmd(s);
                    MessageBox.Show("客户端[追加]完成");
                }
            }
        }
    }

    private void btn_svnupdate_Click(object sender, EventArgs e)
    {
        string path = ConfigManager.ReadIniData("PATH", "value", "");
        if (!valid_svn_cmd())
        {
            MessageBox.Show("请先选择svn_command的路径");
            select_svn_cmd();
            if (!valid_svn_cmd())
            {
                return;
            }
        }
        if (!have_enough_clients())
        {
            MessageBox.Show("客户端不齐全，先点击创建足够的客户端");
            return;
        }

        string s = "@echo off";
        for (int i = 0; i < get_clients_count(); i++)
        {
            if (Directory.Exists(this_path + "\\" + path + (i + 1)))
            {
                string revert = "\"" + get_svn_cmd() + "\\svn.exe\" revert -R " + this_path + "\\" + path + (i + 1) + "\\";
                s += "\n" + revert;
                string update = "\"" + get_svn_cmd() + "\\svn.exe\" update " + this_path + "\\" + path + (i + 1) + "\\";
                s += "\n" + update;
            }
        }
        Utils.do_cmd(s);

        change_channel_tag();
        MessageBox.Show("所有客户端SVN更新完成");
    }

    private void combox_kind_SelectedIndexChanged(object sender, EventArgs e)
    {
    }

    private void combo_opentype_SelectedIndexChanged(object sender, EventArgs e)
    {
    }

    private void combox_globalinfo_SelectedIndexChanged(object sender, EventArgs e)
    {
    }

    private void btn_toggle_Click(object sender, EventArgs e)
    {
        if (!have_enough_clients())
        {
            MessageBox.Show("客户端不齐全，先创建足够的客户端");
            return;
        }

        change_channel_tag();
        copy_lua_files();
        MessageBox.Show("切换完成");
    }

    private void btn_clearaccounts_Click(object sender, EventArgs e)
    {
        string path = ConfigManager.ReadIniData("PATH", "value", "");
        string gameDir = "bole_game_Data\\windows\\Record\\Accounts.json";

        if (!have_enough_clients())
        {
            MessageBox.Show("客户端不齐全，先创建足够的客户端");
            return;
        }
        string s = "@echo off";
        for (int i = 0; i < get_clients_count(); i++)
        {
            if (Directory.Exists(this_path + "\\" + path + (i + 1)))
            {
                string deleteaccount = "del " + this_path + "\\" + path + (i + 1) + "\\" + gameDir;
                s += "\n" + deleteaccount;
            }
        }
        Utils.do_cmd(s);
    }

    private void btn_closeclient_Click(object sender, EventArgs e)
    {
        string path = ConfigManager.ReadIniData("PATH", "value", "");
        string gameExePath = "bole_game.exe";

        if (combo_opentype.SelectedIndex == 0)
        {
            System.Diagnostics.Process[] myProcesses;
            myProcesses = System.Diagnostics.Process.GetProcessesByName("IEXPLORE");
            foreach (System.Diagnostics.Process instance in myProcesses)
            {
                instance.Kill();
            }
        }
        else if (combo_opentype.SelectedIndex == 1)
        {
            string s = "taskkill /F /IM " + gameExePath;
            Utils.do_cmd(s);
        }
    }

    private void checkbox_reopen_CheckedChanged(object sender, EventArgs e)
    {

    }
    private void select_browser_path()
    {
        OpenFileDialog open = new OpenFileDialog();
        if (open.ShowDialog() == DialogResult.OK)
        {
            string foldPath = open.FileName;
            //ConfigManager.WriteIniData("BROWSERPATH", "value", foldPath);

            if (!File.Exists(foldPath))
            {
                MessageBox.Show("浏览器路径错误，请重新选择");
                select_browser_path();
            }
            else
            {
                ConfigManager.WriteIniData("BROWSERPATH", "value", foldPath);
            }
        }
    }

    private void btn_start_Click(object sender, EventArgs e)
    {
        string path1 = ConfigManager.ReadIniData("PATH", "value", "");
        if (combo_opentype.SelectedIndex == 0) //浏览器打开（H5）
        {
            if (checkbox_reopen.Checked) //先关闭
            {
                System.Diagnostics.Process[] myProcesses;
                myProcesses = System.Diagnostics.Process.GetProcessesByName("IEXPLORE");
                foreach (System.Diagnostics.Process instance in myProcesses)
                {
                    instance.Kill();
                }
            }
            string url = ConfigManager.ReadIniData("URL", "value", "");
            int openNum = 0;
            object URL = url;
            int resolutionx = Convert.ToInt32(input_resolutionx.Text);
            int resolutiony = Convert.ToInt32(input_resolutiony.Text);
            ////屏幕分辨率
            System.Drawing.Rectangle rec = Screen.GetWorkingArea(this);
            int SH = rec.Height;
            int SW = rec.Width;

            for (int i = 0; i < listview_c.Items.Count; i++)
            {
                if (listview_c.Items[i].Checked)
                {
                    try
                    { //调用本地IE浏览器打开
                        int rowNumMax = (int)Math.Floor((decimal)SH / (resolutiony + 50));//最大行数
                        int columnNumMax = (int)Math.Floor((decimal)SW / (resolutionx + 50));//最大列数
                        Thread.Sleep(500);

                        Microsoft.ShDocVw.InternetExplorer IE = new Microsoft.ShDocVw.InternetExplorer();
                        IE.Visible = true;
                        if (openNum + 1 <= columnNumMax)
                        {
                            IE.Left = 50 + openNum * (resolutionx + 50);
                            IE.Top = 50 + 0;
                        }
                        else if (openNum + 1 > columnNumMax && openNum + 1 <= columnNumMax * 2)
                        {
                            IE.Left = 50 + (openNum - columnNumMax) * (resolutionx + 50);
                            IE.Top = 50 * 2 + resolutiony;
                        }
                        else if (openNum + 1 > columnNumMax * 2 && openNum + 1 <= columnNumMax * 3)
                        {
                            IE.Left = 50 + (openNum - columnNumMax * 2) * (resolutionx + 50);
                            IE.Top = 50 * 3 + resolutiony;
                        }
                        IE.Width = resolutionx;
                        IE.Height = resolutiony;
                        IE.Navigate2(ref URL, IE.Left, IE.Top, resolutionx, resolutiony);
                    }
                    catch
                    { //若果IE调取失败，这提醒用户手动选择浏览器
                        string url1 = ConfigManager.ReadIniData("BROWSERPATH", "value", "");
                        if (url1 == null || url1 == "")
                        {
                            MessageBox.Show("请先选择用于打开应用的浏览器的路径,并重新开始游戏");
                            select_browser_path();
                        }
                        else
                        {
                            if (checkbox_reopen.Checked) //先关闭
                            {
                                System.Diagnostics.Process[] myProcesses;
                                myProcesses = System.Diagnostics.Process.GetProcessesByName("IEXPLORE");
                                foreach (System.Diagnostics.Process instance in myProcesses)
                                {
                                    instance.Kill();
                                }
                            }
                            Thread.Sleep(300);
                            System.Diagnostics.Process.Start(url1, url);
                        }
                    }
                    openNum++;
                }
            }

        }
        else if (combo_opentype.SelectedIndex == 1) //客户端打开
        {
            if (!have_enough_clients())
            {
                MessageBox.Show("客户端不齐全，先创建足够的客户端");
                return;
            }

            string gameExePath = "bole_game.exe";

            //是否关闭之前的客户端
            if (checkbox_reopen.Checked)
            {
                string s = "taskkill /F /IM " + gameExePath + " \n";
                Utils.do_cmd(s);
            }
            //打开客户端
            int opennum = 0;
            int resolutionx = Convert.ToInt32(input_resolutionx.Text);
            int resolutiony = Convert.ToInt32(input_resolutiony.Text);
            ////屏幕分辨率
            System.Drawing.Rectangle rec = Screen.GetWorkingArea(this);
            int SH = rec.Height;
            int SW = rec.Width;
            int n = SW / resolutionx;
            for (int i = 0; i < listview_c.Items.Count; i++)
            {
                if (listview_c.Items[i].Checked)
                {
                    string path = this_path + "\\" + path1 + (i + 1) + "\\" + gameExePath;
                    int x = 0;
                    int y = 0;
                    if (window_layout_type == 1)
                    {
                        x = 50 + (opennum % n) * resolutionx;
                        y = 50 + (opennum / n) * resolutiony;
                    }
                    else if (window_layout_type == 2)
                    {
                        x = 50 + 50 * opennum;
                        y = 50 + 50 * opennum;
                    }
                    Utils.do_file_open_xy_size(path, x, y, resolutionx, resolutiony);

                    opennum = opennum + 1;
                }
                if (opennum > 0 && opennum % 12 == 0)
                {
                    MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                    DialogResult dr = MessageBox.Show("你已经开了" + opennum + "个客户端了，你确定你的电脑扛得住？", "", messButton);
                    if (dr == DialogResult.Cancel)
                    {
                        break;
                    }
                }
            }
            //保存配置
            ConfigManager.WriteIniData("USER", "kind", combox_kind.Text);
            ConfigManager.WriteIniData("USER", "globalinfo", combox_globalinfo.Text);
            ConfigManager.WriteIniData("USER", "resolutionx", resolutionx.ToString());
            ConfigManager.WriteIniData("USER", "resolutiony", resolutiony.ToString());
            ConfigManager.WriteIniData("USER", "type", combo_opentype.Text);
            string str = "";
            for (int i = 0; i < listview_c.Items.Count; i++)
            {
                str += i > 0 ? "," : "";
                str += listview_c.Items[i].Checked ? "1" : "0";
            }
            ConfigManager.WriteIniData("USER", "clients", str);
            ConfigManager.WriteIniData("USER", "reopen", checkbox_reopen.Checked ? "1" : "0");
        }
    }

    //切换客户端连接地址和kindid
    private void change_globalid_kindid()
    {
        if (combo_opentype.SelectedIndex == 1)
        {
            string path = ConfigManager.ReadIniData("PATH", "value", "");
            string gameDir = "";

            var serializer = new DataContractJsonSerializer(typeof(Buildinfo));
            //读buildinfo
            string str = FileManager.readFile(this_path + "\\" + path + "1" + "\\" + gameDir + "\\StreamingAssets\\windows\\BuildInfo.txt");
            var mStream = new MemoryStream(System.Text.Encoding.Default.GetBytes(str));
            Buildinfo values = (Buildinfo)serializer.ReadObject(mStream);
            //修改
            values.GlobalInfoId = combox_globalinfo.Text;
            values.GameKind = Convert.ToInt32(combox_kind.Text);
            //写buildinfo
            var stream = new MemoryStream();
            serializer.WriteObject(stream, values);
            byte[] dataBytes = new byte[stream.Length];
            stream.Position = 0;
            stream.Read(dataBytes, 0, (int)stream.Length);
            string str_result = System.Text.Encoding.UTF8.GetString(dataBytes);
            FileManager.writeFile(this_path + "\\" + path + "1" + "\\" + gameDir + "\\StreamingAssets\\windows\\BuildInfo.txt", str_result);
            //复制buildinfo
            string s = "@echo off";
            for (int i = 0; i < get_clients_count(); i++)
            {
                if (i == 0) continue;
                if (Directory.Exists(this_path + "\\" + path + (i + 1)))
                {
                    string copyglobalinfo = "xcopy " + this_path + "\\" + path + "1" + "\\" + gameDir + "\\StreamingAssets\\windows\\BuildInfo.txt " + this_path + "\\" + path + (i + 1) + "\\" + gameDir + "\\StreamingAssets\\windows\\BuildInfo.txt /y";
                    s += "\n" + copyglobalinfo;
                }
            }
            Utils.do_cmd(s);
        }
    }

    private void change_channel_tag()
    {
        if (combo_opentype.SelectedIndex == 1)
        {
            string path = ConfigManager.ReadIniData("PATH", "value", "");
            string gameDir = "bole_game_Data\\StreamingAssets\\channel.txt";


            //读channel.txt
            string str = FileManager.readFile(this_path + "\\" + path + "1" + "\\" + gameDir);

            //写channel.txt
            FileManager.writeFile(this_path + "\\" + path + "1" + "\\" + gameDir, combox_globalinfo.Text);
            //复制channel.txt
            string s = "@echo off";
            for (int i = 1; i < get_clients_count(); i++)
            {
                if (i == 0) continue;
                if (Directory.Exists(this_path + "\\" + path + (i + 1)))
                {
                    string srcPath = this_path + "\\" + path + "1\\" + gameDir;
                    string targetPath = this_path + "\\" + path + (i + 1) + "\\" + gameDir;
                    string copyglobalinfo = "xcopy " + srcPath + " " + targetPath + " /y";
                    s += "\n" + copyglobalinfo;
                }
            }
            Utils.do_cmd(s);
        }
    }

    //复制配置表
    private void copy_lua_files()
    {
        string path = ConfigManager.ReadIniData("PATH", "value", "");
        string gameDir = "bole_game_Data\\StreamingAssets\\windows\\Lua";

        string s = "@echo off";
        for (int i = 1; i < get_clients_count(); i++)
        {
            if (Directory.Exists(this_path + "\\" + path + (i + 1)))
            {
                string srcPath = this_path + "\\" + path + "1\\" + gameDir;
                string targetPath = this_path + "\\" + path + (i + 1) + "\\" + gameDir;
                string copylua = "xcopy " + srcPath + "\\*.lua " + targetPath + " /s /e /h /y";
                s += "\n" + copylua;
            }
        }
        Utils.do_cmd(s);
    }

    //是否已经有足够客户端
    private bool have_enough_clients()
    {
        string path = ConfigManager.ReadIniData("PATH", "value", "");
        for (int i = 0; i < get_clients_count(); i++)
        {
            if (!Directory.Exists(this_path + "\\" + path + (i + 1)))
            {
                return false;
            }
        }
        return true;
    }
    //获取配置的客户端数
    private int get_clients_count()
    {
        string clientcount = ConfigManager.ReadIniData("CLIENT_COUNT", "value", "");
        if (clientcount == "")
        {
            ConfigManager.WriteIniData("CLIENT_COUNT", "value", "4");
            clientcount = "4";
        }
        return Convert.ToInt32(clientcount);
    }
    //获取svn_cmd路径
    private string get_svn_cmd()
    {
        string svn_cmd = ConfigManager.ReadIniData("SVNCOMMAND", "value", "");
        return svn_cmd;
    }
    //svn_command路径是否可用
    private bool valid_svn_cmd()
    {
        if (File.Exists(get_svn_cmd() + "\\svn.exe"))
        {
            return true;
        }
        return false;
    }

    private void select_svn_cmd()
    {
        FolderBrowserDialog dialog = new FolderBrowserDialog();
        dialog.Description = "请选择svn_command路径";
        if (dialog.ShowDialog() == DialogResult.OK)
        {
            string foldPath = dialog.SelectedPath;
            if (!File.Exists(foldPath + "\\svn.exe"))
            {
                MessageBox.Show("svn_command路径错误，请重新选择");
                select_svn_cmd();
            }
            else
            {
                ConfigManager.WriteIniData("SVNCOMMAND", "value", foldPath);
            }
        }
    }

    private void radiobtn_pingpu_CheckedChanged(object sender, EventArgs e)
    {
        window_layout_type = 1;
    }

    private void radiobtn_cengdie_CheckedChanged(object sender, EventArgs e)
    {
        window_layout_type = 2;
    }

    private void MainForm_Load(object sender, EventArgs e)
    {

    }
}